<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { LowcodeGroovyApi } from '#/api/lowcode/groovy';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { Page } from '@vben/common-ui';
import { isEmpty } from '@vben/utils';

import { message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteGroovyScript,
  getGroovyScriptPage,
  updateScriptStatus,
} from '#/api/lowcode/groovy';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';

const router = useRouter();

/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 创建脚本 */
function handleCreate() {
  // 直接跳转到编辑器页面创建新脚本
  router.push({
    name: 'LowcodeGroovyEditor',
  });
}

/** 编辑脚本 - 统一使用编辑器页面 */
function handleEdit(row: LowcodeGroovyApi.GroovyScript) {
  router.push({
    name: 'LowcodeGroovyEditor',
    query: { id: row.id },
  });
}

/** 删除脚本 */
async function handleDelete(row: LowcodeGroovyApi.GroovyScript) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.name]),
    key: 'action_key_msg',
  });
  try {
    await deleteGroovyScript(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.name]),
      key: 'action_key_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: LowcodeGroovyApi.GroovyScript[];
}) {
  checkedIds.value = records.map((item) => item.id as number);
}

/** 批量删除脚本 */
async function handleDeleteBatch() {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting'),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    // TODO: 实现批量删除API
    // await deleteGroovyScriptList(checkedIds.value);
    checkedIds.value = [];
    message.success($t('ui.actionMessage.deleteSuccess'));
    onRefresh();
  } finally {
    hideLoading();
  }
}

/** 更新脚本状态 */
async function handleStatusChange(
  newStatus: number,
  row: LowcodeGroovyApi.GroovyScript,
): Promise<boolean | undefined> {
  return new Promise((resolve, reject) => {
    updateScriptStatus(row.id as number, newStatus)
      .then(() => {
        message.success($t('ui.actionMessage.operationSuccess'));
        resolve(true);
      })
      .catch((error) => {
        reject(error);
      });
  });
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(handleStatusChange),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getGroovyScriptPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<LowcodeGroovyApi.GroovyScript>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
</script>

<template>
  <Page auto-content-height>
    <Grid table-title="脚本列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: $t('ui.actionTitle.create', ['脚本']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['lowcode:groovy:create'],
              onClick: handleCreate,
            },
            {
              label: '批量删除',
              type: 'primary',
              danger: true,
              disabled: isEmpty(checkedIds),
              icon: ACTION_ICON.DELETE,
              auth: ['lowcode:groovy:delete'],
              onClick: handleDeleteBatch,
            },
          ]"
        />
      </template>
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['lowcode:groovy:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['lowcode:groovy:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [
                  row.displayName || row.scriptName,
                ]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
